package cn.tedu._03vehicle.base.interceptors;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalTime;

@Slf4j
public class TimeAccessInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("进入时间访问拦截器...");
        LocalTime now = LocalTime.now(); //获取当前系统时间;
        int hour = now.getHour();
        if (hour<6 || hour>22){
            //方案1:抛出异常,并使用全局异常处理器处理该异常;
            //throw new RuntimeException("必须在06:00-22:59分之间进行访问");
            //方案2:重定向到错误页面 http://localhost:8080/error.html
            response.sendRedirect("/error.html");
            return false;
        }

        return true; //放行
    }
}
